package com.jewaton.authmanage.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

public class CustomSecurityMetadataSource implements
		FilterInvocationSecurityMetadataSource {
	
	private HashMap<String, Collection<ConfigAttribute>> resMap = new HashMap<String, Collection<ConfigAttribute>>();
	
	public CustomSecurityMetadataSource(){
		loadResourceDefine();
	}
	
	/**
	 * 加载资源
	 */
	public void loadResourceDefine(){
		Collection<ConfigAttribute> configAttrs = new ArrayList<ConfigAttribute>();
		
		ConfigAttribute cfgAttr = new SecurityConfig("ROLE_ADMIN");
		configAttrs.add(cfgAttr);
		
		resMap.put("/home", configAttrs);
		
		configAttrs = new ArrayList<ConfigAttribute>();
		cfgAttr = new SecurityConfig("ROLE_ADMIN");
		configAttrs.add(cfgAttr);
		cfgAttr = new SecurityConfig("ROLE_USER");
		configAttrs.add(cfgAttr);
		
		resMap.put("/", configAttrs);
		
	}

	/**
	 * 根据路径获取访问权限
	 */
	@Override
	public Collection<ConfigAttribute> getAttributes(Object object)
			throws IllegalArgumentException {
		HttpServletRequest request = ( (FilterInvocation) object ).getHttpRequest();
		RequestMatcher matcher = null;
		String resUrl = null;
		for (Iterator<String> it =  resMap.keySet().iterator();it.hasNext();) {
			resUrl = it.next();
			matcher = new AntPathRequestMatcher(resUrl);
			if(null != resUrl && matcher.matches(request)){
				return resMap.get(resUrl);
			}
		}
		return null;
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		Collection<ConfigAttribute> configAttrs = new ArrayList<ConfigAttribute>();
		for (Collection<ConfigAttribute> cas : resMap.values()) {
			configAttrs.addAll(cas);
		}
		return configAttrs;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}

}
